package top.fullj.actor.mq;

import java.util.concurrent.Executor;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * single thread executor
 */
class ThreadExecutorFiber implements Fiber, Comparable<ThreadExecutorFiber> {

    private static Executor newExecutor() {
        ThreadPoolExecutor executor = new ThreadPoolExecutor(0, 1,
                30L, TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(Short.MAX_VALUE),
                new FiberThreadFactory());
        executor.allowCoreThreadTimeOut(true);
        return executor;
    }

    private final Executor executor;
    private final AtomicInteger ref = new AtomicInteger();

    ThreadExecutorFiber() {
        this.executor = newExecutor();
    }

    @Override
    public void execute(Runnable command) {
        this.executor.execute(command);
    }

    @Override
    public void start() {
        ref.incrementAndGet();
    }

    @Override
    public void dispose() {
        ref.decrementAndGet();
    }

    @Override
    public int compareTo(ThreadExecutorFiber o) {
        return ref.get() - o.ref.get();
    }

}
